using System.Data;
using System.Windows.Forms;
using backfile.util;
using System;
using System.Data.SQLite;
using System.ComponentModel;

using System.Threading;
using System.Collections.Generic;
using Timer = System.Threading.Timer;
using System.Threading.Tasks;
using backfile.job;

namespace backfile
{
    public partial class MainForm : Form
    {
        private string dbname = "backfile.db";
        private int allCount = 0;  //总条数
        private int pagesize = 20;  //每页展示条目数
        private int pagecount = 0;  //总页数
        private int page = 1;  //当前页数

        public static MainForm instance;

        public MainForm()
        {
            InitializeComponent();

            ReadLog("启动程序");
            SQLiteconn();
            IsExistDB();
            IsExistTable();
            initView();
            instance = this;

            resetTask();
            RunTask();
        }

        private  void SQLiteconn()
        {
            SQLiteHelper.LocalDbConnectionString = "Data Source=" + dbname;
        }

        private void initView() {
            //DataSet ds = getAllDataSet();
            //this.dataGridView1.DataSource = ds.Tables[0];
            DataTable ds = SelectPaging();
            this.dataGridView1.DataSource = ds;
            this.label3.Text = "总条数："+ allCount + "条";

            pagecount = allCount % pagesize;

            if (pagecount == 0)
            {
                pagecount = allCount / pagesize;
            }
            else
            {
                pagecount = allCount / pagesize + 1;
            }

            this.label5.Text = "共"+ pagecount+"页";
            this.label4.Text = "当前第"+page+"页";


        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex > 0)
            {
                DataGridViewColumn column = dataGridView1.Columns[e.ColumnIndex];
                if (column is DataGridViewButtonColumn)
                {
                    //这里可以编写你需要的任意关于按钮事件的操作~
                    //MessageBox.Show("按钮被点击");
                    //this.dataGridView1.CurrentRow.Visible=false;//隐藏当前行
                    this.dataGridView1.Rows.RemoveAt(e.RowIndex);//删除当前行
                }
            }
        }

        private void dataGridView1_CellMouseUp(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                if (e.RowIndex >= 0)
                {
                    dataGridView1.ClearSelection();
                    dataGridView1.Rows[e.RowIndex].Selected = true;
                    dataGridView1.CurrentCell = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];
                    contextMenuStrip1.Show(MousePosition.X, MousePosition.Y);
                }
            }

        }

       /// <summary>
       /// 显示日志
       /// </summary>
       /// <param name="log"></param>
        private void ReadLog(string log)
        {
            if (log.Length > 0) {
                //DateTime dt = DateTime.Now;
                //string Time = DateTime.Now.ToUniversalTime().ToString();
                string Time = string.Format("{0:yyyy-MM-dd HH:mm:ss}", DateTime.Now);
                richTextBox1.AppendText(Time + "  " + log + "\n");
            }
        }

        public void ReadMainLog(string log)
        {
            this.BeginInvoke(new Action<string>((message) =>
            {
                ReadLog(message);
            }), log);
        }

        /// <summary>
        /// 判断数据文件是否存在
        /// </summary>
        private void IsExistDB()
        {
            if (!FileUtil.IsExistFile(dbname))
            {
                ReadLog(dbname + "数据文件不存在...");
                CreateDB();
            }
        }

        /// <summary>
        /// 判断表是否存在
        /// </summary>
        private void IsExistTable()
        {
            string sql = "select name from sqlite_master where name='task'";
            DataSet ds = SQLiteHelper.ExecuteDataSet(SQLiteHelper.LocalDbConnectionString,sql, CommandType.Text);
            //SQLiteCommand cmd = new SQLiteCommand();
            //cmd.CommandText = sql;
            //DataSet ds = SQLiteHelper.ExecuteDataSet(SQLiteHelper.LocalDbConnectionString, cmd);
            //Console.Write(ds.ToString());
            //ReadLog(ds.Tables[0].Rows.Count.ToString());
            if (ds == null || ds.Tables[0].Rows.Count == 0) 
            {
                CreateTable();
            }

        }

        /// <summary>
        /// 创建数据文件
        /// </summary>
        private void CreateDB()
        {
            SQLiteHelper.CreateDbFile(dbname);
            ReadLog("创建" + dbname + "数据文件成功");
        }

        /// <summary>
        /// 创建表
        /// </summary>
        private void CreateTable()
        {
            string sql = " CREATE TABLE task (id INTEGER PRIMARY KEY AUTOINCREMENT,title varchar,start_date varchar, next_date varchar,source_dir varchar,target_dir varchar,interval INTEGER,is_compress varchar,is_delete varchar,ignore_file TEXT,state INTEGER)";
            SQLiteHelper.ExecuteNonQuery(SQLiteHelper.LocalDbConnectionString, sql, CommandType.Text);
            ReadLog("创建task表成功");

        }
        /// <summary>
        /// 获取任务列表
        /// </summary>
        /// <returns></returns>
        private DataSet getAllDataSet()
        {
            string sql = "select * from task";
            DataSet ds = SQLiteHelper.ExecuteDataSet(SQLiteHelper.LocalDbConnectionString, sql, CommandType.Text);
            return ds;
        }
        /// <summary>
        /// 分页查询
        /// </summary>
        /// <returns></returns>
        private DataTable SelectPaging()
        {
            DataTable ds = SQLiteHelper.SelectPaging(SQLiteHelper.LocalDbConnectionString, "task", "id,title,start_date,next_date,source_dir,target_dir,interval,is_compress,is_delete,ignore_file","id > 0","id desc", pagesize, page, out allCount);
            return ds;
        }

        private void resetTask()
        {
            string sql = "update task set state = 0 ";
            //MessageBox.Show(sql);
            int rs = SQLiteHelper.ExecuteNonQuery(SQLiteHelper.LocalDbConnectionString, sql, CommandType.Text);
            if (rs >= 0)
            {
                ReadLog("重置任务状态成功");
            }
            else
            {
                ReadLog("重置任务状态失败");
            }

        }




        private void label1_Click(object sender, System.EventArgs e)
        {

        }

        private void label4_Click(object sender, EventArgs e)
        {

        }
        /// <summary>
        /// 首页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            page = 1;
            initView();
        }
        /// <summary>
        /// 上一页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void linkLabel3_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            page--;
            if (page > 0)
            {
                initView();
            }
            else
            {
                MessageBox.Show("现已是第一页记录");
                page = pagecount;
                return;
            }
        }
        /// <summary>
        /// 下一页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void linkLabel4_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            page++;
            if (page <= pagecount)
            {
                initView();
            }
            else
            {
                MessageBox.Show("现已是最后一页记录");
                page = pagecount;
                return;
            }
        }
        /// <summary>
        /// 末页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            page = pagecount;
            initView();
        }

        /// <summary>
        /// 刷新
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void linkLabel5_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            initView();
            MessageBox.Show("刷新成功");
        }
        /// <summary>
        /// 新增任务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void newtask_Click(object sender, EventArgs e)
        {
            Form2 f = new Form2();
            f.ShowDialog();
            if (f.DialogResult == DialogResult.OK)
            {
                initView();
            }
        }
        /// <summary>
        /// 清空日志
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            richTextBox1.Text = "";
        }
        /// <summary>
        /// 主窗体加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainForm_Load(object sender, EventArgs e)
        {

        }
       

        /// <summary>
        /// 关闭按钮事件
        /// </summary>
        /// <param name="e"></param>
        protected override void OnClosing(CancelEventArgs e)
        {
            DialogResult result = MessageBox.Show("是否确认关闭？", "提示",
                                    MessageBoxButtons.YesNo, MessageBoxIcon.Information);
            e.Cancel = result != DialogResult.Yes;
            //System.Environment.Exit(0);
            resetTask();
            base.OnClosing(e);
        }

        private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DialogResult dr = MessageBox.Show("确认删除吗？","提示",MessageBoxButtons.OKCancel);
            if (dr == DialogResult.OK)
            {
                 try
                {

                    int index = this.dataGridView1.CurrentRow.Index;
                    string id = this.dataGridView1.Rows[index].Cells[0].Value.ToString();
                    if (string.IsNullOrEmpty(id))
                    {
                        MessageBox.Show("没有数据可删除");
                        return;
                    }
                    string sql = "delete from task where id = " + id;
                    //MessageBox.Show(sql);
                    int rs = SQLiteHelper.ExecuteNonQuery(SQLiteHelper.LocalDbConnectionString, sql, CommandType.Text);
                    MainForm.instance.ReadMainLog("删除任务ID：" + id + ",标题：" + this.dataGridView1.Rows[index].Cells[1].Value.ToString());
                    MessageBox.Show("删除成功");
                    initView();
                }
                catch (Exception )
                {
                    MessageBox.Show("没有数据可删除");
                }

            }
        }

        /// <summary>
        /// 获取可执行的任务
        /// </summary>
        /// <returns></returns>
        private  DataSet getExecTask()
        {
            string sql = "select * from task where next_date <='"+ string.Format("{0:yyyy-MM-dd HH:mm:ss}", DateTime.Now) + "' and state = 0  order by next_date asc limit 5";
            DataSet ds = SQLiteHelper.ExecuteDataSet(SQLiteHelper.LocalDbConnectionString, sql, CommandType.Text);
            //MainForm.instance.ReadMainLog(SQLiteHelper.LocalDbConnectionString+",sql:"+ sql);
            //Console.Write(sql);
            return ds;
        }

        /// <summary>
        /// 异步执行任务
        /// </summary>
        /// <returns></returns>
        public static void RunTask()
        {
            Task parent = new Task(async () =>
        {

            string sql;
            DataSet ds;
            int count;

            while (true)
            {
                sql = "select * from task where next_date <='" + string.Format("{0:yyyy-MM-dd HH:mm:ss}", DateTime.Now) + "' and state = 0  order by next_date asc limit 5";
                ds = SQLiteHelper.ExecuteDataSet(SQLiteHelper.LocalDbConnectionString, sql, CommandType.Text);

                count = ds.Tables[0].Rows.Count;

                Console.WriteLine("count=" + count.ToString());
                if (count > 0)
                {
                    List<Task> Tasks = new List<Task>();
                        //int i = 0;
                        foreach (DataRow mDr in ds.Tables[0].Rows)
                    {
                        Dictionary<string, string> taskData = new Dictionary<string, string>();
                        foreach (DataColumn mDc in ds.Tables[0].Columns)
                        {
                            taskData.Add(mDc.ToString(), mDr[mDc].ToString());

                        }
                        string updatesql = "update task set state = 1 where id = " + taskData["id"];
                        int rs = SQLiteHelper.ExecuteNonQuery(SQLiteHelper.LocalDbConnectionString, updatesql, CommandType.Text);
                            //runBackUp(taskData,i);
                            Tasks.Add(Task.Run(() => runBackUp(taskData)));
                            Thread.Sleep(1000 * 3);
                        //taskData.Clear();
                        //tasks[i] = Task.Factory.StartNew(() => runBackUp(taskData, i));
                        //i++;

                    }
                        //Task.WaitAll(tasks);
                        await Task.WhenAll(Tasks);
                }

                Thread.Sleep(1000 * 5);

            }
        });
            parent.Start();
        }
        private static  void runBackUp(Dictionary<string, string> taskData)
        {
            BackUp.run(taskData);
           // foreach (KeyValuePair<string, string> kv in taskData)

            //{
            //    Console.WriteLine(kv.Key + ":" + kv.Value);
            //}
        }

   

    }
}
